// JobAlumnuInfo.js
import React from 'react'
import PropTypes from 'prop-types'
import { View, Text, ScrollView, StyleSheet, TextInput } from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import CustomButton from 'src/components/button/CustomButton'
import { ImageViewer } from 'react-native-image-zoom-viewer'
import CustomImage from 'src/components/image/CustomImage'
import { CommonToast } from 'src/utils/ToastUtil'
import { showSelectModal, showModal, showTipModal } from 'src/utils/ModalUtil'
import { openCamera, multipleAlums } from 'src/utils/ImagePickerUtil'
import { DismissLoading, ShowLoading } from '../../../utils/ToastUtil'
import { isArrayFn } from 'src/utils/JSTypeUtil'
import { reportPost, uploadImage, getPostDetail } from 'src/utils/RequestAPI'
import BasePage from 'src/pageP/base/base-page/index'
import { connect } from 'react-redux'
import { generateFuzzyQuery } from 'src/utils/FuzzyQueryUtil'
import {
  ScaleS,
  ScaleT,
  ONE_PIXEL,
  NAVIGATIONBAR_HEIGHT,
  HEIGHT
} from 'src/utils/ScreenUtil'
@connect(
  ({ userinfo, landmark, jobDetailStore, im, CMineCenterStore }) => ({
    userinfoC: userinfo.C,
    userinfo,
    landmark
  })
)
class CompanyReport extends BasePage {
  static propTypes = {
    reportClick: PropTypes.func
  }

  constructor(props) {
    super(props)
    this.state = {
      initIndex: 0,
      reason: '',
      contact: '',
      header: {},
      height: 30,
      basicInfo: {},
      reportType: undefined,
      dataArr: [],
      list: ['电话虚假', '非法收费', '职位虚假', '涉黄违法', '招聘刷单', '冒充直招', '招生培训信息 (非招聘)', '其他']
    }
    this.selectModalConfig = {
      selectArr: [
        {
          label: '相册上传'
        },
        {
          label: '拍照上传'
        }],
      titleText: '添加照片',
      onCancel: this._selectModalCancel,
      selectClick: this._selectModalClick
    }
  }

  componentDidFocus() {

  }
  componentDidMount() {
    const { navigation: { state: { params: { jobDetailId } } } } = this.props
    if (jobDetailId) {
      getPostDetail({
        params: {
          postId: jobDetailId
        }
      })
        .then(data => {
          const jobDetail = data.data
          if (jobDetail && jobDetail.basicInfo) {
            jobDetail.basicInfo.isFast = jobDetail.isFast
          }
          jobDetail.basicInfo.companyName = jobDetail.companyInfo.simpleName || jobDetail.companyInfo.companyName
          jobDetail.basicInfo.postId = jobDetail.id
          jobDetail.basicInfo.companyId = jobDetail.companyId
          this.setState({
            basicInfo: (jobDetail || {}).basicInfo
          })
        })
        .then(datas => { })
        .finally(() => {
          DismissLoading()
        })
    }
  }

  _imageViewerRef = (imageViewerRef) => {
    this.imageViewerRef = imageViewerRef
  }

  _uploadImgClick = () => {
    if ((this.state.dataArr || []).length >= 6) {
      CommonToast('最多只能上传六张')
    } else {
      this._toggleSelectModal(true)
    }
  }

  _selectModalCancel = () => {
    this._toggleSelectModal(false)
  }

  _toggleSelectModal = (selectModalShow, callBack) => {
    if (selectModalShow) {
      this.selectModal = showSelectModal(this.selectModalConfig)
    } else {
      if (this.selectModal) {
        this.selectModal.close(() => {
          callBack && callBack()
        })
      }
    }
  }

  _selectModalClick = index => {
    switch (index) {
      case 0:
        this.selectModal.close(() => {
          const maxFiles = 6 - (this.state.dataArr || []).length
          multipleAlums({ maxFiles }).then((images) => {
            this._addImage(images)
          })
        })
        break
      case 1:
        this.selectModal.close(() => {
          openCamera({
            width: 750, height: 750
          }).then((image) => {
            this._addImage(image)
          })
        })
        break
      default:
        this.selectModal.close()
    }
  }

  generator = function* (images) {
    for (let i = 0; i < images.length; i++) {
      yield uploadImage({ params: { uri: images[i].imgPath, type: 'profile', mime: images[i].mime } })
    }
  }

  _addImage = (img) => {
    if (isArrayFn(img)) {
      this._uploadImages(img)
    } else {
      this._uploadImages([img])
    }
  }

  _uploadImages = (images) => {
    ShowLoading()
    const iterator = this.generator(images)
    const userArchiveImgModels = []

    function handle(iteratorResult) {
      if (iteratorResult.done) {
        if (userArchiveImgModels.length > 0) {
          this._uploadImage(userArchiveImgModels)
        } else {
          DismissLoading()
        }
        return
      }
      const iteratorValue = iteratorResult.value
      if (iteratorValue instanceof Promise) {
        iteratorValue.then((res) => {
          userArchiveImgModels.push(res.data)
          handle.call(this, iterator.next())
        }).catch(() => {
          handle.call(this, iterator.next())
        })
      }
    }

    handle.call(this, iterator.next())
  }

  _uploadImage = (userArchiveImgModels = []) => {
    const { navigation: { state: { params } } } = this.props
    const oldArrs = this.state.dataArr.map((item) => {
      return item.noHostUrl
    })
    const newArrs = [...userArchiveImgModels, ...oldArrs]
    this.setState({
      dataArr: newArrs
    })
    DismissLoading()
  }

  onReportType = ({ index }) => {
    this.setState({
      reportType: index
    })
  }

  cause = (e) => {
    this.setState({
      reason: e
    })
  }

  inform = () => {
    const { reportType, dataArr, reason, contact, list, basicInfo } = this.state
    if (dataArr.length > 0 && reportType !== undefined) {
      if (reportType === 7 && reason.length === 0) {
        CommonToast('请填写举报原因')
        return
      }

      const params = { userName: this.props.userinfoC.userName, postId: basicInfo.postId, companyId: basicInfo.companyId, reason: reportType === 7 ? reason : list[reportType], img: dataArr.join(','), contact }
      reportPost({ params }).then((res) => {
        if (this.props.navigation.state.params.onPress) {
          this.props.navigation.state.params.onPress()
        }
        if (res.code == 200) { this.props.navigation.goBack() }
        CommonToast('举报成功')
      })
    } else {
      CommonToast('请把举报类型与原因填写完整')
    }
  }

  contact = (e) => {
    this.setState({
      contact: e
    })
  }

  onClick = ({ index }) => {
    const inglist = this.state.dataArr.filter((item, i) => i !== index)
    this.setState({
      dataArr: inglist
    })
  }

  childRender() {
    let { list, dataArr, basicInfo, reportType, reason, contact } = this.state
    return (
      <View style={styles.container}>

        <KeyboardAwareScrollView enableAutomaticScroll={true}
          keyboardShouldPersistTaps="handled" contentContainerStyle={{ padding: ScaleS(20) }}>
          <Text style={styles.postHeader}>岗位举报</Text>
          <View style={styles.companyPost}>
            <View style={styles.companyView}>
              <Text>
                公司:
              </Text>
              <Text>{basicInfo.companyName}</Text>
            </View>
            <View style={styles.companyView}>
              <Text>岗位:</Text>
              <Text>{basicInfo.name}</Text>
            </View>
          </View>
          <Text>请选择举报类型</Text>
          <View style={styles.customButtonList}>
            {
              list.map((item, index) => {
                return <CustomButton onPress={this.onReportType} params={{ index }} style={[styles.customButton, reportType === index && { borderColor: '#48BD7C' }]} key={index} >
                  <Text style={[styles.customButtonText, reportType === index && { color: '#48BD7C' }]}>{item}</Text>
                </CustomButton>
              })
            }
          </View>
          {
            !!(reportType === 7) && <View style={styles.text}>
              <TextInput
                style={styles.contactInput}
                value={reason || ''}
                placeholder='请详细说明信息，有助于我们更快速地核实您的举报'
                placeholderTextColor={'#bbbbbb'}
                underlineColorAndroid={'transparent'}
                maxLength={120}
                multiline
                ref={textInput => this.TextInput = textInput}
                onChangeText={this.cause} />
              <Text style={styles.contactSize}>{(reason || '').length}/120</Text>
            </View>
          }
          <View>
            <Text>
              凭证 (最多可上传6张）
            </Text>
            <View style={{ width: '100%', minHeight: ScaleS(100), marginTop: ScaleS(24), marginBottom: ScaleS(24), flexDirection: 'row', flexWrap: 'wrap' }}>
              {
                (dataArr || []).map((item, index) => {
                  return <View style={styles.headView} key={index}>
                    <View key={index} style={styles.itemView} >
                      <CustomImage style={styles.itemImg} source={{ uri: item }} />
                    </View>
                    <CustomButton style={styles.deleteIcon} onPress={this.onClick} params={{ index: index }}>
                      <CustomImage style={{ resizeMode: 'cover' }} source={require('@/imgC/userinfo/close-black.png')} />
                    </CustomButton>
                  </View>
                })
              }
              {
                !!((dataArr || []).length < 6) && <CustomButton style={styles.uploadImgView} onPress={this._uploadImgClick}>
                  <CustomImage style={styles.uploadImg} source={require('@/imgC/userinfo/add_black.png')} />
                </CustomButton>
              }
            </View>
          </View>
          <View>
            <Text>
              联系方式 (选填)
            </Text>
            <TextInput
              onChangeText={this.contact}
              value={contact || ''}
              placeholder='留下您的联系方式，方便为您答疑解惑'
              style={styles.mobile} />
          </View>
          <View style={styles.reportView}>
            <CustomButton onPress={this.inform} style={[styles.report, reportType !== undefined && dataArr.length > 0 && { backgroundColor: '#000' }]}><Text style={[styles.reportText, reportType !== undefined && dataArr.length > 0 && { color: '#fff' }]}>举报</Text></CustomButton>
          </View>
        </KeyboardAwareScrollView>
      </View>
    )
  }
}
export default CompanyReport
const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: ScaleS(10)
  },
  report: {
    width: '100%',
    height: ScaleS(50),
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: ScaleS(4),
    marginTop: ScaleS(20),
    backgroundColor: '#EBEBEB'
  },
  reportView: {
    width: '100%'
  },
  postHeader: {
    fontSize: ScaleT(27),
    fontWeight: '500',
    marginBottom: ScaleS(24),
    color: '#444444'
  },
  reportText: {
    fontWeight: '500',
    color: '#999999'
  },
  companyView: {
    flexDirection: 'row',
    marginBottom: ScaleS(18)
  },
  customButtonList: {
    marginTop: ScaleS(30),
    flexDirection: 'row',
    flexWrap: 'wrap'
  },
  customButton: {
    borderColor: '#979797',
    borderWidth: ONE_PIXEL,
    borderRadius: ScaleS(2),
    minWidth: ScaleS(72),
    paddingBottom: ScaleS(6),
    paddingTop: ScaleS(6),
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: ScaleS(5),
    marginBottom: ScaleS(20),
    paddingHorizontal: ScaleS(8)

  },
  companyPost: {
    borderColor: '#CDCDCD',
    borderWidth: ONE_PIXEL,
    paddingHorizontal: ScaleS(14),
    paddingTop: ScaleS(18),
    marginBottom: ScaleS(30)
  },
  mobile: {
    marginTop: ScaleS(24),
    borderWidth: ONE_PIXEL,
    borderColor: '#979797',
    paddingHorizontal: ScaleS(20),
    height: ScaleS(44),
    fontSize: ScaleT(14)
  },
  uploadImgView: {
    width: ScaleS(100),
    height: ScaleS(100),
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: ONE_PIXEL,
    borderColor: '#979797',
    flexDirection: 'row',
    marginTop: ScaleS(5),
    paddingHorizontal: ScaleS(20),
    borderRadius: ScaleS(5),
    marginBottom: ScaleS(26)
  },
  uploadImg: {
    width: ScaleS(14),
    height: ScaleS(14)
  },
  uploadText: {
    color: '#000000',
    fontSize: ScaleT(14),
    fontWeight: '400',
    marginLeft: ScaleS(9)
  },
  itemView: {
    width: ScaleS(100),
    height: ScaleS(100),
    marginRight: ScaleS(1),
    marginBottom: ScaleS(1),
    alignItems: 'center'
  },
  customButtonText: {
    color: '#999999'
  },
  itemImg: {
    width: ScaleS(100),
    height: ScaleS(100),
    resizeMode: 'cover',
    borderRadius: ScaleS(4)
  },
  text: {
    borderWidth: ONE_PIXEL,
    borderColor: '#979797',
    alignItems: 'center',
    height: ScaleS(137)
  },
  contactSize: {
    color: '#CCCCCC',
    position: 'absolute',
    bottom: ScaleS(20),
    right: ScaleS(20)
  },
  contactInput: {
    width: ScaleS(295),
    paddingVertical: ScaleS(0),
    paddingLeft: ScaleS(5),
    fontSize: ScaleT(16),
    height: ScaleS(137)
  },
  deleteIcon: {
    backgroundColor: '#000',
    width: ScaleS(15),
    height: ScaleS(15),
    borderRadius: ScaleS(7),
    position: 'absolute',
    top: ScaleS(0),
    right: ScaleS(0),
    zIndex: 99999,
    justifyContent: 'center',
    alignItems: 'center'
  },
  headView: {
    width: ScaleS(105),
    height: ScaleS(105),
    marginRight: ScaleS(10),
    justifyContent: 'flex-end',
    alignItems: 'flex-start'
  }
})
